import axios from 'axios'
import qs from 'qs'
import {getLocalStorageStr} from './index'
import store from '@/store/index'
import {apiUrl} from '@/config'
import {ElMessage} from 'element-plus'
import router from '@/router/index'

const instance = axios.create({
    baseURL: apiUrl,
    timeout: 60000000
})

export const down = async (url, data = {}) => {
    const res = await initRequestHeader('get', url, data)
    data = res.data
    return new Promise((resolve, reject) => {
        instance.get(res.url, {params: data, headers: res.headers, responseType: 'blob'}).then((response) => {
            if (response.data.code == 401) {
                // 登录超时
                store.dispatch('logout')
            } else {
                resolve(response)
            }
        }, err => {
            reject(err)
        })
    })
}

export const get = async (url, data = {}) => {
    const res = await initRequestHeader('get', url, data)
    data = res.data
    return new Promise((resolve, reject) => {
        instance.get(res.url, {params: data, headers: res.headers}).then((response) => {
            if (response.data.code == 401) {
                // 登录超时
                store.dispatch('logout').then(()=>{
                    ElMessage({
                        message: '登录超时，请重新登录.',
                        type: 'error'
                    })
                    router.push('/login')
                })
            } else if (response.data.code === 500) {
                const msg = response.data.msg
                ElMessage({
                    message: (msg != null && msg.length > 300) ? msg.substring(0, 300) : msg || '系统异常，请重试',
                    type: 'error'
                })
                reject(response)
            } else {
                resolve(response.data)
            }
        }, err => {
            console.log(err.response)
            ElMessage({
                message: (err && err.response) ? err.response.statusText : '连接异常，请重试',
                type: 'error'
            })
            reject(err)
        })
    })
}

export const post = async (url, data = {}, type = 'urlencoded') => {
    const res = await initRequestHeader('post', url, data, type)
    return new Promise((resolve, reject) => {
        instance.post(res.url, res.data, {
            headers: res.headers
        }).then((response) => {
            if (response.data.code === 500) {
                const msg = response.data.msg
                ElMessage({
                    message: (msg != null && msg.length > 300) ? msg.substring(0, 300) : msg || '系统异常，请重试',
                    type: 'error'
                })
                reject(response)
            }
            resolve(response.data)
        }, err => {
            ElMessage({
                message: (err && err.response) ? err.response.statusText : '连接异常，请稍后再试',
                type: 'error'
            })
            reject(err)
        })
    })
}

/**
 * 初始化请求头和数据
 * date 2022-08-15
 */
const initRequestHeader = async (method, url, data = {}, type = 'urlencoded') => {
    let result = {}
    let headers = {}

    //用户登录状态下，判断是否需要更新access_token
    if (getLocalStorageStr('accessToken')) {
        const cur_time = parseInt(new Date().getTime() / 1000)
        if (cur_time - getLocalStorageStr('accessTokenExp') * 1 >= 0) {
            const param = new FormData()
            param.append('grant_type', 'refresh_token')
            param.append('refresh_token', getLocalStorageStr('refreshToken'))
            await instance.post('/v1/oauth/oauth/token', param, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'Authorization': 'Basic eWxyLW1hbmFnZXItcGM6MTY4MDAxODYwMTE='
                }
            }).then((res) => {
                if (res.data.code == 200) {
                    store.dispatch('refreshToken', res)
                }
            }, err => {
                console.log('更新access_token出错：', err)
            })
        }
    }

    if (method == 'post') {
        if (type == 'urlencoded') {
            headers = {'Content-Type': 'application/x-www-form-urlencoded'}
            data = qs.stringify(data)
        } else if (type == 'json') {
            headers = {'Content-Type': 'application/json'}
            data = JSON.parse(JSON.stringify(data))
        } else if (type == 'form') {//form-data
            headers = {'Content-Type': 'multipart/form-data'}
            const tmp_data = new FormData()
            Object.keys(data).forEach((item) => {
                tmp_data.append(item, data[item])
            })
            data = tmp_data
        }
    }

    if (url.indexOf('/v1/oauth/oauth/token') > -1) {
        headers.Authorization = 'Basic eWxyLW1hbmFnZXItcGM6MTY4MDAxODYwMTE='
    } else {
        const token = getLocalStorageStr('accessToken')
        headers.Authorization = 'Bearer ' + token
    }
    // console.log('url:' + url)
    // console.log('reqData:' + JSON.stringify(data))
    // console.log('headers:' + JSON.stringify(headers))
    result = {url, data, headers}
    return result
}

export default instance
